//
//  SoundDetailViewController.m
//  HuiYinMaster
//
//  Created by Icloud-Zhanyong on 2017/4/24.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "SoundDetailViewController.h"
#import "SoundDetailHeaderView.h"
#import "SoundPlayTableViewCell.h"
#import "SoundOneTableViewCell.h"
#import "SoundTwoTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import "AFNetWorking.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "SeverManager.h"

#import "SoundPlayTool.h"


@interface SoundDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>


@property(nonatomic,strong)UITableViewCell * cell;

@property(nonatomic,strong)SoundPlayTableViewCell * playCell;

@property(nonatomic,strong)AVPlayer * player;

@property (nonatomic,strong) UITapGestureRecognizer * tapGesture;


@property(nonatomic,strong)SoundPlayTool * avPlayer;

//@property(nonatomic,strong)VoiceListModel * currentModel;

@property(nonatomic,strong) NSTimer * timer;

@property(nonatomic,strong)UISlider * slider;

@end

@implementation SoundDetailViewController

- (void)viewDidLoad {
    [self getAucherInfo];
    
    self.avPlayer = [SoundPlayTool shareSoundPlay];
    
    self.avPlayer.voiceDataArray = self.voiceDataArray;
    
    //判断id是否发生变化 改变了就重新播放
    if (self.avPlayer.currentModel.id != self.voiceDetailModel.id ){
        
        self.avPlayer.currentModel = self.voiceDetailModel;
        
        self.avPlayer.currentId = self.voiceDetailModel.playID;
        
        [self.avPlayer play];
        
    }else{
//        返回的时候会移除观察 所以要添加一次
        [[SoundPlayTool shareSoundPlay] addPlayLoadTime];
        [[SoundPlayTool shareSoundPlay] addPlayStatus];
    }

//    //获取音频会话11
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    //设置类型是播放。
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    //激活音频会话。
//    [session setActive:YES error:nil];
    
    [super viewDidLoad];
    
    [self creatUI];
//    
//    [self loadData];
//    
//    self.currentId = 0;
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    // Do any additional setup after loading the view.
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(upDateInfo) userInfo:nil repeats:YES];
}

-(void)upDateInfo {
    self.voiceSlider.value = [SoundPlayTool shareSoundPlay].playProgress;
    self.voiceProgress.progress = [SoundPlayTool shareSoundPlay].loadProgress;
    self.playCell.voiceCurrentTimeLabel.text = [SoundPlayTool shareSoundPlay].currentTime;
    self.playCell.VioceDurationLabel.text = [SoundPlayTool shareSoundPlay].totalTime;
}
-(NSMutableArray *)voiceDataArray
{
    if (_voiceDataArray == nil){
        _voiceDataArray = [[NSMutableArray alloc]init];
    }
    return _voiceDataArray;
}


-(void)loadData{
    
    }
-(void)reloadUI{
    self.voiceSlider.value = 0;
    self.voiceProgress.progress = 0;
    [self.BaseTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 禁用  返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = false;
}
-(void)creatUI{
    
    self.BaseTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.BaseTableView.delegate = self;
    self.BaseTableView.dataSource = self;
    self.BaseTableView.showsVerticalScrollIndicator = false;
     _playCell = [SoundPlayTableViewCell fastLoginView];
    self.BaseTableView.tableHeaderView = _playCell;
    [_playCell.VoiceDetailBackButton addTarget:self action:@selector(SoundDetBackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.voiceSlider = [[UISlider alloc]init];
    self.voiceProgress = [[UIProgressView alloc]init];
    [self.voiceSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    [self.voiceSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateHighlighted];
    
    self.voiceProgress.trackTintColor = [UIColor whiteColor];
    self.voiceProgress.progressTintColor = [UIColor grayColor];
    
    self.voiceSlider.minimumTrackTintColor = XMColor(108, 34, 42);
    self.voiceSlider.maximumTrackTintColor = [UIColor clearColor];
    
    [_playCell addSubview:self.voiceProgress];
    [self.voiceProgress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_playCell.mas_left).offset(1);
        make.right.mas_equalTo(_playCell.mas_right).offset(-1);
        make.top.mas_equalTo(_playCell.headerImgView.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    
    [_playCell addSubview:self.voiceSlider];
    [self.voiceSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_playCell.mas_left).offset(1);
        make.right.mas_equalTo(_playCell.mas_right).offset(-1);
        make.top.mas_equalTo(_playCell.headerImgView.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    [self.voiceSlider addTarget:self action:@selector(sliderChangeValue:) forControlEvents:UIControlEventValueChanged];
    
    [_playCell.voicePlayOrStopButton addTarget:self action:@selector(voicePlayOrStopButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    _playCell.voicePlayOrStopButton.selected = YES;
    [_playCell.upVoiceButton addTarget:self action:@selector(upButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_playCell.nextVoiceButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
}


-(void)upButtonClick{
    [self.avPlayer upVoiceButtonClick];
    self.playCell.voicePlayOrStopButton.selected = YES;
}
-(void)nextButtonClick{
    [self.avPlayer nextVoiceButtonClick];
    self.playCell.voicePlayOrStopButton.selected = YES;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     if (indexPath.row == 0){
        UITableViewCell * cell = [[UITableViewCell alloc]init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        view.backgroundColor = XMColor(249, 249, 249);
        [cell addSubview:view];
        return  cell;
    }
    //声音所属专辑
    else if (indexPath.row == 1){
        SoundOneTableViewCell * cell = [SoundOneTableViewCell fastLoginView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",port,_voiceDetailModel.imgUrl]];
        [cell.SoundImage sd_setImageWithURL:imageUrl];
        cell.SoundTitleLabel.text = self.voiceDetailModel.title;
        return cell;
    }else if (indexPath.row == 2) {
        UITableViewCell * cell = [[UITableViewCell alloc]init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = XMColor(249, 249, 249);
        return  cell;
    //声音简介内容
    }else {
        SoundTwoTableViewCell * cell = [SoundTwoTableViewCell fastLoginView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.SoundBlongLabel.text = self.voiceDetailModel.title;
//        cell.SoundContentLabel.text = self.voiceDetailModel.content;
        return  cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 10;
    }else if(indexPath.row == 1){
        return 80;
    }else if (indexPath.row == 2){
        return 3;
    }else {
        return 200;
    }
}

//返回
-(void)SoundDetBackButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
    [[SoundPlayTool shareSoundPlay] removePlayStatus];
    [[SoundPlayTool shareSoundPlay] removePlayLoadTime];
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark -拉动滑条改变进度
-(void)sliderChangeValue:(UISlider *)sender{
    //根据值计算时间
    float time = sender.value * CMTimeGetSeconds([SoundPlayTool shareSoundPlay].avPlayer.currentItem.duration);
    //跳转到当前指定时间
    [[SoundPlayTool shareSoundPlay].avPlayer seekToTime:CMTimeMake(time, 1)];
}


#pragma mark -播放暂停
-(void)voicePlayOrStopButtonClick:(UIButton *)sender{
    if(!sender.selected){
        [self.avPlayer goOnPlay];
        sender.selected = YES;
    }else{
        [self.avPlayer pause];
        sender.selected = false;
    }
}

-(void)actionTapGesTrue:(UITapGestureRecognizer *)sender{
    CGPoint touchPoint = [sender locationInView:_voiceSlider];
    CGFloat value = (_voiceSlider.maximumValue - _voiceSlider.minimumValue) * (touchPoint.x / _voiceSlider.frame.size.width );
    [_voiceSlider setValue:value animated:YES];
}

#pragma mark -获取headerView和个人简介
-(void)getAucherInfo{
    //实例化sesionManager
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    //调出请求头
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //将请求头封装进去
    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appId"];
    [manager GET:aucherInfo parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"getAucherInfo %@",responseObject);
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        self.aucherInfoModel = [[AucherInfoModel alloc]initWithDict:dic];
        NSString * imageStr = [NSString stringWithFormat:@"%@%@",port,self.aucherInfoModel.faceUrl];
        NSURL * imageUrl = [NSURL URLWithString:imageStr];
        //        NSLog(@"headerImgUrl%@",self.headerImgUrl);
        [self.playCell.headerImgView sd_setImageWithURL:imageUrl];
        //        NSLog(@"首页header图片%@",imageUrl);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure");
    }];
}

//-(void)dealloc {
//    
//    [self.timer invalidate];
//    self.timer = nil;
//}

@end
